import  router  from '@/router'
import { useUserStore } from '../stores/user';
import { postRefreshToken } from '@/api/auth'

let subscribers: Function[] = []
let isRefreshing = false

// 缓存token失效时发起的请求
export const cacheNoneTokenRequestList = (request: Function) => {
  subscribers.push(request)
}

// 刷新token之后，重新发起之前token失效时发起的请求
export const retryRequest = () => {
  subscribers.forEach(request => request())
  subscribers = []
}

// 无感刷新token
export const refreshAccessToken = async () => {
  if (!isRefreshing) {
    isRefreshing = true
    const userStore = useUserStore()

    try {
      if (userStore.refreshToken) {
        // 刷新token，获取新的access_token
        const { data } = await postRefreshToken(null, {
          headers: { RefreshToken: userStore.refreshToken }
        })
        userStore.setToken(data.access_token)
        retryRequest()
      }
      return
    } catch (err) {
      // 清除token，并跳转到登录页
      userStore.setToken('')
      userStore.setRefreshToken('')
      router.replace('/login')
      return
    } finally {
      isRefreshing = false
    }
  }
}
